package com.feizhi.inventory.fragment.Inventorydetails.inventoryprofitfragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aserbao.aserbaosandroid.functions.database.greenDao.db.DaoSession;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.HistoryDetailsDao;
import com.aserbao.aserbaosandroid.functions.database.greenDao.db.TaskDetailsDao;
import com.feizhi.inventory.MainActivity;
import com.feizhi.inventory.R;
import com.feizhi.inventory.bean.InventoryDetailsBean;
import com.feizhi.inventory.database.HistoryDetails;
import com.feizhi.inventory.database.TaskDetails;
import com.feizhi.inventory.database.dbApp;
import com.feizhi.inventory.databinding.FragmentInventoryProfitBinding;
import com.feizhi.inventory.fragment.Inventorydetails.InventoryProfitAdapter;
import com.feizhi.inventory.util.ThreadPool;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 盘盈 fragment
 */
public class InventoryProfitFragment extends Fragment {

    private List<InventoryDetailsBean> data;
    boolean isDuplicate = false;
    private List<TaskDetails> details;
    private TaskDetailsDao taskDetailsDao;
    private List<HistoryDetails> historyDetails = new ArrayList<>();
    private HistoryDetailsDao historyDetailsDao;
    List<HistoryDetails> lists;
    private InventoryProfitAdapter adapter;
    private FragmentInventoryProfitBinding mBinding;
    private MainActivity mActivity;

    private String taskID;
    private String postRfid;
    private String taskID1;
    private String id;
    private String name;
    private String spec;
    private String epcID;
    private String savePlace;
    private String custodian;
    private String department;
    private String state;
    private List<TaskDetails> taskDetailsList = new ArrayList<>();
    private List<TaskDetails> listsss;
    private TaskDetails taskDetails;
    private List<TaskDetails> saoCodeList;

    public InventoryProfitFragment() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = FragmentInventoryProfitBinding.inflate(inflater);
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化操作
        initView();
        //事件处理
        setOnClickListener();
    }

    private void setOnClickListener() {


        adapter.setItemOnClickListener(new InventoryProfitAdapter.OnClickListener() {
            @Override
            public void ItemOnClickListener(int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", taskDetailsList.get(position).getId());
//                        Log.d("我想再再再看看", "id: " + taskDetailsList.get(position).getId());
                bundle.putString("name", taskDetailsList.get(position).getName());
                bundle.putString("spec", taskDetailsList.get(position).getSpec());
                bundle.putString("eps_id", taskDetailsList.get(position).getEpcID());
                bundle.putString("save_place", taskDetailsList.get(position).getSavePlace());
                bundle.putString("custodian", taskDetailsList.get(position).getCustodian());
                bundle.putString("department", taskDetailsList.get(position).getDepartment());
                bundle.putString("state", taskDetailsList.get(position).getState());
                bundle.putString("notes_1", taskDetailsList.get(position).getNotes_1());
                bundle.putString("notes_2", taskDetailsList.get(position).getNotes_2());
                bundle.putString("notes_3", taskDetailsList.get(position).getNotes_3());
                bundle.putString("type", taskDetailsList.get(position).getType());
                bundle.putString("inputDate", taskDetailsList.get(position).getInputDate());
                Navigation.findNavController(mActivity, R.id.fragment_my).navigate(R.id.itemDetailsFragment, bundle);
            }
        });
    }

    private void initView() {

        DaoSession daoSession = ((dbApp) mActivity.getApplicationContext()).getDaoSession();
        historyDetailsDao = daoSession.getHistoryDetailsDao();
        taskDetailsDao = daoSession.getTaskDetailsDao();
//        onRefresh();

        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new InventoryProfitAdapter(taskDetailsList);
        mBinding.recyclerView.setAdapter(adapter);

        LiveEventBus.get().with("search_condition3", String.class).observe(this, new Observer<String>() {

            @Override
            public void onChanged(String s) {
                saoCodeList = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),
                        TaskDetailsDao.Properties.State.eq("盘盈")).list();
                List<TaskDetails> condition = new ArrayList<>();
                taskDetailsList.clear();
                for (int i = 0; i < saoCodeList.size(); i++) {

                    if (saoCodeList.get(i).getName().contains(s)) {
                        taskDetailsList.add(saoCodeList.get(i));
                    }

                }
                int mateSize = taskDetailsList.size();
                Toast.makeText(mActivity, "为您搜索到" + mateSize + "条数据", Toast.LENGTH_SHORT).show();
                adapter.setData(taskDetailsList);

            }
        });

        LiveEventBus.get().with("postRfid", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                if (TextUtils.isEmpty(s)) {
                    postRfid = "";
                }else {
                    postRfid = s;
                }

                onRefresh();

            }
        });


        LiveEventBus.get().with("Task_ID", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

                taskID = s;

                onRefresh();
                listsss = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),
                        TaskDetailsDao.Properties.State.eq("盘盈")).list();
                if (!taskDetailsList.isEmpty()) {
                    taskDetailsList.clear();
                }

                taskDetailsList.addAll(listsss);
                adapter.setData(taskDetailsList);

            }
        });


    }

    public void onRefresh() {
        refresh();

    }

    private void refresh() {


        try {

            ThreadPool.runThread(() -> {


                    //listsss = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.State.eq("盘盈")).list();

                    if (TextUtils.isEmpty(postRfid)) {
                        return;
                    }
                    try {
                        listsss = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),
                                TaskDetailsDao.Properties.EpcID.eq(postRfid)).list();

                        lists = historyDetailsDao
                                .queryBuilder()
                                .where(HistoryDetailsDao.Properties.EpcID.eq(postRfid))
                                .list();

                        for (TaskDetails taskDetails1 : listsss) {
                            if (taskDetails1.getEpcID().equals(postRfid)) {
                                isDuplicate = true;
                                break;
                            }
                        }

                        if (!isDuplicate) {

                            taskID1 = taskID;
                            if (TextUtils.isEmpty(id)) {
                                id = "";
                            }
                            id = lists.get(0).getId();
                            name = lists.get(0).getName();
                            spec = lists.get(0).getSpec();
                            epcID = lists.get(0).getEpcID();
                            savePlace = lists.get(0).getSavePlace();
                            custodian = lists.get(0).getCustodian();
                            department = lists.get(0).getDepartment();
                            state = lists.get(0).getState();
                            taskDetails = new TaskDetails(
                                    taskID,
                                    id,
                                    name,
                                    department,
                                    spec,
                                    listsss.get(0).getType(),
                                    custodian,
                                    listsss.get(0).getInputDate(),
                                    savePlace,
                                    epcID,
                                    lists.get(0).getNotes_1(),
                                    lists.get(0).getNotes_2(),
                                    lists.get(0).getNotes_3()
                                    ,"未盘点");


                            taskDetailsDao.insert(taskDetails);

                        }

                    }catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        listsss = taskDetailsDao.queryBuilder().where(TaskDetailsDao.Properties.TaskID.eq(taskID),TaskDetailsDao.Properties.State.eq("盘盈")).list();

                        if (!taskDetailsList.isEmpty()) {
                            taskDetailsList.clear();
                        }

                        taskDetailsList.addAll(listsss);
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.setData(taskDetailsList);
                            }
                        });
                    }catch (Exception e) {
                        e.printStackTrace();
                    }


            });

        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}